from urllib.parse import quote_plus
from pymongo import MongoClient
from pymongo.errors import OperationFailure
from bson.son import SON
import pandas as pd
def get_database_info(database_name,collection_name):
    # 数据表定义
    #columns = ['Database', 'Collection', 'Document Count', 'Collection Size (bytes)']
    columns = ['Srcontent', 'Pushtime']
    df = pd.DataFrame(columns=columns)

    # MongoDB 连接信息
    mongo_host = 'xxxxxxxx'
    mongo_port = 3717
    mongo_user = 'rwuser'
    mongo_password = 'xxxxxx'
    escaped_password = quote_plus(mongo_password)
    escaped_host = quote_plus(mongo_host)

    # 连接 MongoDB
    connection_string = f'mongodb://{mongo_user}:{escaped_password}@{mongo_host}:{mongo_port}/admin'
    client = MongoClient(connection_string)

    # 指定要获取信息的数据库
    db = client[database_name]

    # 获取数据库中所有集合
    collection = db[collection_name]
    query = {"isRelease":"yes", "pushtime": { "$lte" : "2020-01-01 00:00:00"},"srcontent":{ "$regex":  "gif"}}
    update_query = {"$set": {"isRelease": "no"}}
    results = collection.update_many(query, update_query)
    count = 0
    for result in results:
      try:
        print(result)
        count = count + 1
        print("=================================")
        df = df.append({'Srcontent': result['srcontent'], 'Pushtime': result['pushtime']}, ignore_index=True)
      except OperationFailure as op_err:
        print(f"OperationFailure for collection: {op_err}")
    print(count)
    df.to_csv("out.csv", index=False)

if __name__ == "__main__":
    # 指定要获取信息的数据库名称
    database_name = "bdpinterface"
    collection_name = "contentlib"
    get_database_info(database_name, collection_name)